import * as echarts from 'echarts';
import { ref , toRefs , markRaw , onMounted, reactive , onBeforeUnmount , onActivated , watch , nextTick} from 'vue';
interface Params {
    props: any;
    option: any;
}
function useEcharts(params: Params) {
    const {  props , option } = params;
    const chartRef = ref();

    const state = reactive({
        chart: null as any,
        nvll: ['',null,undefined],
    })
    
    onMounted(() => {
        //initChart();
        window.addEventListener('resize',echartsResizeFun);
    });
    
    onActivated(() => {
        echartsResizeFun();
    });
    
    watch(() => [props.data , props.theme ], () => {
        nextTick(() => {
            initChart();
        });
    }, {deep: true , immediate: true});
    
    function initChart() {
        if(state.nvll.indexOf(state.chart) === -1) state.chart.dispose();
        state.chart = markRaw(echarts.init(chartRef.value,props.theme));
        state.chart.setOption(option);
    }
    
    function echartsResizeFun() {
        state.chart && state.chart.resize();
    }
    
    onBeforeUnmount(() => {
        window.removeEventListener('resize',echartsResizeFun);
        if(state.chart) {
            state.chart.dispose();
            state.chart = null;
        }
    })
    return {
        chartRef,
        ...toRefs(state),
        echartsResizeFun,
    }
}
export default useEcharts;
export { useEcharts};